package middleware

import (
	"gitee.com/Cauchy_AQ/vxopen/api/internal/common"
	"gitee.com/Cauchy_AQ/vxopen/rpc/transform/transformer"
	"github.com/zeromicro/go-zero/rest/httpx"
	"net"
	"net/http"
	"strings"
)

type CaptchaLimitMiddleware struct {
	Transformer transformer.Transformer
}

func NewCaptchaLimitMiddleware(transformers transformer.Transformer) *CaptchaLimitMiddleware {
	return &CaptchaLimitMiddleware{
		Transformer: transformers,
	}
}

func (m *CaptchaLimitMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		ip := getClientIp(r)
		rpcResp, err := m.Transformer.CaptchaWithIp(r.Context(), &transformer.CaptchaWithIpReq{
			Ip: ip,
		})
		if err != nil || !rpcResp.Ok {
			httpx.Error(w, common.NewCodeError(common.RefreshCaptchaCode, common.CodeRefreshCaptcha))
			return
		}
		next(w, r)
	}
}

func getClientIp(r *http.Request) string {
	ip := strings.TrimSpace(strings.Split(r.Header.Get("X-Forwarded-For"), ",")[0])
	if ip != "" {
		return ip
	}
	if ip = r.Header.Get("X-Real-IP"); ip != "" {
		return ip
	}
	if ip, _, err := net.SplitHostPort(r.RemoteAddr); err == nil {
		return ip
	}
	return ""
}
